package xin.marcher.module.replenished.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xin.marcher.module.common.constants.diplomacy.AbstractRedisKeyConstants;
import xin.marcher.module.common.core.JsonResult;
import xin.marcher.module.inventory.domain.response.WarningInventoryDTO;
import xin.marcher.module.replenished.redis.RedisReadWriteManager;
import xin.marcher.module.replenished.redis.RedisSortedSetCache;
import xin.marcher.module.replenished.repository.RedisManagerRepository;
import xin.marcher.module.replenished.service.WarningInventoryService;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 库存预警 业务实现类
 *
 *
 */
@Service
public class WarningInventoryServiceImpl implements WarningInventoryService {

    @Autowired
    private RedisReadWriteManager redisReadWriteManager;

    @Autowired
    private RedisManagerRepository redisManagerRepository;

    @Override
    public JsonResult warningInventory(WarningInventoryDTO warningInventoryDTO) {
        List<Long> sellerIdList = Arrays.asList(warningInventoryDTO.getSellerId());
        //1.查询缓存,key为卖家ID，value为对应的sku列表
        Map<Long, List<String>> redisSetMap = redisReadWriteManager.getRedisSortedSet(sellerIdList, AbstractRedisKeyConstants::getWarningInventoryZsetKey);
        //2. 获取这个卖家下的库存预警商品列表
        List<String> skuList = redisSetMap.get(warningInventoryDTO.getSellerId());
        //3. 返回缓存操作的模型对象
        Map<String, RedisSortedSetCache> redisSortedSetCacheMap = redisManagerRepository.diffWarningInventory(skuList, warningInventoryDTO, AbstractRedisKeyConstants::getWarningInventoryZsetKey);
        if (redisSortedSetCacheMap.size() > 0) {
            //4 执行数据缓存更新
            redisReadWriteManager.flushIncrSortedSetMap(redisSortedSetCacheMap);
            return JsonResult.buildSuccess();
        }

        return JsonResult.buildError("重复库存预警通知");
    }
}
